var ue;

$(document).keydown(function (e) {
    var keycode = e.keyCode;
    if (keycode == 13) {
        $("#btnSearch").click();
    }
});

$(document).delegate("#btnSearch", "click", function () {
    $("#table").bootstrapTable('refresh');
});


//公告列表===========================================================================================================


function initTable() {
    var url = "/manage/notice/list";
    $('#table').bootstrapTable({
        url: url,
        striped: true,
        cache: false,
        pagination: true,
        sidePagination: "server",
        toolbar: "#toolbar",
        pageList: [10, 25, 50, 100],
        columns: [{
            checkbox: true,
            align: 'center',
        }, {
            field: 'noticeId',
            title: '公告 ID'
        }, {
            field: 'noticeName',
            title: '公告名称'
        }, {
            field: 'noticeType',
            title: '公告类型',
            formatter: function (value, row, index) {
                if ("1" == value) {
                    return '<span class="label label-success" style="font-size:12px;">登录公告</span>';
                    return "上线";
                } else if ("2" == value) {
                    return '<span class="label label-default" style="font-size:12px;">首页公告</span>';
                    return "下线";
                }
            }
        }, {
            field: 'status',
            title: '状态',
            formatter: function (value, row, index) {
                if ("1" == value) {
                    return '<span class="label label-success" style="font-size:12px;">上线</span>';
                    return "上线";
                } else if ("2" == value) {
                    return '<span class="label label-default" style="font-size:12px;">下线</span>';
                    return "下线";
                } else {
                    return '<span class="label label-default" style="font-size:12px;">未上线</span>';
                    return "未上线";
                }
            }
        }, {
            field: 'startTime',
            title: '开始时间'
        }, {
            field: 'endTime',
            title: '结束时间'
        }, {
            field: 'noticeId',
            title: '操作',
            formatter: function (value, row) {
                var result = "";
                result += "<a href='javascript:;' class='btn btn-xs green' onclick=\"noticeView(" + JSON.stringify(row).replace(/\"/g, "'") + ")\"><span class='glyphicon glyphicon-search'></span> 预览</a>";
                result += "<a href='javascript:Base.dialogIframe(\"公告编辑\" ,\"/manage/notice/modify/@noticeId\")' class='btn btn-xs'><span class='glyphicon glyphicon-pencil'></span> 编辑</a>";
                result += "<a href='javascript:noticeDeleteDialog(\"@noticeId\", \"@noticeName\")' class='btn btn-xs text-danger'><span class='glyphicon glyphicon-remove'></span> 删除</a>";

                result = result.replace(/@noticeId/g, value);
                result = result.replace(/@noticeName/g, row.noticeName);

                return result;
            }
        }],
        responseHandler: function (res) {
            return res.data;
        },
        queryParams: function (params) {
            var searchkey = $.trim($("#searchkey").val());
            var status = $("#status").val();
            var temp = {
                pageSize: params.limit,
                pageNum: (params.offset / params.limit) + 1,
                sort: params.sort,
                searchkey: searchkey,
                status: status
            };
            return temp;
        },
    });
}

function reflashTable() {
    $("#table").bootstrapTable('refresh');
}

function noticeView(info) {
    top.$.notify({
        // options
        icon: 'glyphicon glyphicon-bullhorn',
        title: info.noticeName,
        message: info.noticeContent
    }, {
        // settings
        type: 'info',
        position: 'fixed',
        placement: {
            from: "bottom",
            align: "left"
        },
        animate: {
            enter: 'animated fadeInUp',
            exit: 'animated fadeOutDown'
        },
        delay: 10000
    });
}

function noticeDeleteDialog(noticeId, noticeName) {
    BootstrapDialog.show({
        title: '删除确认',
        message: '请再次确认是否删除公告【' + noticeName + '】',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-primary',
            action: function (dialog) {
                noticeDelete(noticeId);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function onlineBatchDialog() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要上线的功能！");
        return;
    }

    BootstrapDialog.show({
        title: '批量上线确认',
        message: '请再次确认是否进行批量上线操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                noticeOnline();
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function offlineBatchDialog() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要下线的功能！");
        return;
    }

    BootstrapDialog.show({
        title: '批量下线确认',
        message: '请再次确认是否进行批量下线操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                noticeOffline();
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function exportDialog() {
    BootstrapDialog.show({
        title: '导出确认',
        message: '请再次确认是否进行导出操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                var searchkey = $.trim($("#searchkey").val());
                var status = $("#status").val();
                var param = {
                    searchkey: searchkey,
                    status: status
                };
                Base.executeExport("/manage/notice/export", param);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}


//公告新增修改===========================================================================================================


function initNoticeAddPage() {
    initLaydate();

    ue = UE.getEditor('noticeContent');

    initBootstrapValidator(noticeAdd);
}

function initNoticeModifyPage() {
    initLaydate();

    ue = UE.getEditor('noticeContent');

    initBootstrapValidator(noticeModify, "modify");
}

function initLaydate() {
    laydate.render({
        elem: '#startTime'
    });

    laydate.render({
        elem: '#endTime'
    });
}

function initBootstrapValidator(submitFunc, type) {
    var option = {
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            noticeId: {
                message: '公告名验证失败',
                validators: {
                    notEmpty: {
                        message: '公告ID不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: '公告名长度必须在6到30之间'
                    },
                    threshold: 6, //有6字符以上才发送ajax请求
                    remote: { //{"valid",true}代表有效，{"valid",false}代表无效，
                        url: '/manage/notice/checkexist',
                        message: '公告已存在',
                        delay: 2000,
                        type: 'POST'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '公告名由数字字母下划线和.组成'
                    }
                }
            },
            noticeName: {
                validators: {
                    notEmpty: {
                        message: '公告名称不能为空'
                    }
                }
            }
        }
    };

    if (type == "modify") {
        delete option.fields.noticeId;
    }

    $('form').bootstrapValidator(option).on('success.form.bv', function (e) {
        e.preventDefault();
        submitFunc();
    });

    $('#resetBtn').click(function () {
        $('form').data('bootstrapValidator').resetForm(true);
    });
}


//ajax提交===========================================================================================================


function noticeAdd() {
    var data = $('form').serializej();

    data['noticeContent'] = ue.getContent();

    Base.ajax({
        "url": "/manage/notice/add",
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("公告新增成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("公告新增失败！");
            }
        }
    });
}

function noticeModify() {
    var data = $('form').serializej();

    Base.ajax({
        "url": "/manage/notice/modify",
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("公告修改成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("公告修改失败！");
            }
        }
    });
}

function noticeDelete(noticeId) {
    Base.ajax({
        "url": "/manage/notice/delete",
        "data": {
            "noticeId": noticeId
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("功能删除成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("功能删除失败！");
            }
        }
    });
}


function noticeOnline() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要上线的功能！");
        return;
    }

    var noticeIds = [];
    $.each(selections, function (id, item) {
        noticeIds.push(item.noticeId);
    });
    noticeIds = noticeIds.join(",");

    Base.ajax({
        "url": "/manage/notice/online",
        "data": {
            "noticeIds": noticeIds
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("批量上线成功！");
                reflashTable();
            } else {
                tiperror("批量上线失败！");
            }
        }
    });
}

function noticeOffline() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要下线的功能！");
        return;
    }

    var noticeIds = [];
    $.each(selections, function (id, item) {
        noticeIds.push(item.noticeId);
    });
    noticeIds = noticeIds.join(",");

    Base.ajax({
        "url": "/manage/notice/offline",
        "data": {
            "noticeIds": noticeIds
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("批量下线成功！");
                reflashTable();
            } else {
                tiperror("批量下线失败！");
            }
        }
    });
}


